package com.me.blood.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.adapter.XyHisAdapter;
import com.me.ad.ADType;
import com.me.bean.Xy;
import com.me.blood.databinding.AcXtHistoryBinding;
import com.me.db.DBListener;
import com.me.db.XyDao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class XyHistory extends BaseActivity {

    AcXtHistoryBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = AcXtHistoryBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.title.setText("血压历史记录");

        binding.back.setOnClickListener(view -> finish());
        binding.list.setLayoutManager(new LinearLayoutManager(this));

        new XyDao().getAll(new DBListener() {
            @Override
            public void onResult(boolean bo, String msg, Object result) {
                if (result instanceof Map && !((Map) result).isEmpty()) {
                    List<String> day = (List) ((Map<?, ?>) result).get("day");
                    List<List<Xy>> data = (List) ((Map<?, ?>) result).get("data");
                    List list = new ArrayList();
                    for (int i = 0; i < day.size(); i++) {
                        list.add(day.get(i));
                        list.addAll(data.get(i));
                    }
                    h.post(() -> update(list));
                } else {
                    h.post(() -> update(Collections.emptyList()));
                }
            }
        });
    }

    XyHisAdapter adapter;

    private void update(List list) {
        adapter = new XyHisAdapter(this, list);
        binding.list.setAdapter(adapter);
    }

    int position;

    public void jump(int i, Xy item) {
        position = i;
        Intent in = new Intent(this, InputPressActivity.class);
        in.putExtra("data", item);
        startActivityForResult(in, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            RecyclerView.ViewHolder holder = binding.list.findViewHolderForAdapterPosition(position);
            if (holder instanceof XyHisAdapter.ItemHolder) {
                long id = ((XyHisAdapter.ItemHolder) holder).delete(position);
                if (id != -1) {
                    new XyDao().delete(id);
                }
            }
        }
    }

    @Override
    protected ADType getXpType() {
        return ADType.RECORD_XP;
    }
}
